<template>
    <div class="gradeList">
        <div class="header">
            <el-button type="primary" @click="handleSingleClass">添加班级</el-button>
            <el-button type="primary" @click="handleAdd">导入班级</el-button>
            <el-button type="danger" @click="deleteAll">批量删除</el-button>
            <el-dialog v-if="isSingle" title="用户信息" :visible.sync="dialogAddVisible">
                <div class="dialogAdd">
                    <FormAdd :gradeData="gradeData" @transfer="getInfo" :teacherData="teacherData" :courseCombinationData="courseCombinationData" :currentPage = "currentPage" :pageSize="pageSize" btnMsg="添加单个班级" @success="doNext"></FormAdd>
                </div>
            </el-dialog>
            <el-dialog title="用户信息" v-else :visible.sync="dialogAddVisible">
                <div class="dialogAdd">
                    <FormAdd :currentPage = "currentPage" :pageSize="pageSize" btnMsg="添加班级" @success="doNext"></FormAdd>
                </div>
            </el-dialog>
            <el-input placeholder="输入关键字搜索" v-model="search" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="findUser"></el-button>
            </el-input>
        </div>
        <el-table :data="classList" ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange"
            height="520" style="width: 90%;padding: 20px;margin: 0 auto;">
            <!-- <el-table-column prop="classId" label="班级ID" width="160" show-overflow-tooltip>
            </el-table-column> -->
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="className" label="班级名称" width="160" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="课程组合" prop="combinationName" width="180">
                <!-- <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                        <p>该班级的课程组合:</p>
                        <p>{{ scope.row.address }}132456</p>
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{ scope.row.name }}</el-tag>
                        </div>
                    </el-popover>
                </template> -->
            </el-table-column>
            <el-table-column prop="courseTeacher" label="任课教师" width="160" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="teacherName" label="班主任" width="160" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" width="160">
                <template slot-scope="scope">
                    <div style="display: flex;flex-direction: row;">
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog title="班级信息" :visible.sync="dialogFormVisible">
            <el-form :model="editInfo" :rules="rules" ref="editForm">

                <el-form-item label="班主任:" filterable  :label-width="formLabelWidth" prop="password">
                      <el-select v-model="teacherValue" filterable placeholder="请选择">
                        <el-option
                        v-for="item in teacherData"
                        :key="item.id"
                        :label="item.teacherName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="课程组合:" :label-width="formLabelWidth" prop="email">
                    <el-select v-model="courseCombinationValue" placeholder="请选择">
                        <el-option
                        v-for="item in courseCombinationData"
                        :key="item.id"
                        :label="item.combinationName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeInfo('editForm')">确 定</el-button>
            </div>
        </el-dialog>

        <div class="pages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                 :page-size="pageSize" layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
    </div>
</template>
  
<script>
import FormAdd from '../FormAdd.vue';

export default {
    name: 'GradePage',
    components: {
        FormAdd,
    },
    data() {
        return {
            isSingle: true,
            msg: '班级管理',
            classList: [],
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            // 搜索
            search: '',
            pageArr: [],
            // 编辑
            editInfo: {
                className: "",
                classId:"",
                courseCombination:"",
                gradeId:"",
                headTeacher:"",
                schoolId:"",
            },
            gradeData: [],
            dialogFormVisible: false,
            dialogAddVisible: false,
            dialogAddSingleVisible: false,
            formLabelWidth: '120px',
            teacherData: [],
            courseCombinationData: [],
            schoolId: '',
            teacherValue: '',
            courseCombinationValue: '',
            multipleSelection: [],
            rules: {
            
            },
        }
    },
    methods: {
        getInfo(msg) {
            console.log(msg);
        },
        async getList() {
            console.log(this.teacherData);
            // post
            this.pageArr = [];
            let result = await this.$axios.post(`http://39.105.215.62:8200/class/selectClasses?pageSize=${this.pageSize}&pageNum=${this.currentPage}`, { schoolId: 1, gradeId: 0 });
            console.log(result);
            this.total = result.data.total;
            console.log(this.total);
            for(let i = 0 ; i < Math.ceil(result.data.total / 10); i++) {
                this.pageArr.push((i + 1) * 10);
            }
            this.classList = result.data.records;
        },
        async getCourseCombination() {
            let res = await this.$axios.post(`http://39.105.215.62:8200/courseCombination/selectCourseCombinations?pageSize=12&pageNum=1&schoolId=${this.schoolId}`);
            console.log(res);
            if(res.data) {
                let arr = res.data.records;
                this.courseCombinationData = arr.map(item => {
                    let obj = {};
                    obj.combinationName = item.combinationName;
                    obj.id = item.id;
                    return obj;
                })
            }
        },
        async getTeachaers() {
            let obj = {
                classId: 0,
                courseId: 0,
                schoolId: 1,
                teacherId: 0,
                teacherName: "",
                teacherPhone: "",
                teacherWxid: ""
            }
            // 在这个地方缺少一个获取所有教师的接口，那么当的pageSize返回的是-1的时候，获取的所有教师的信息
            let result = await this.$axios.post("http://39.105.215.62:8100/teacher/findTeachers?pageNum=0&pageSize=10", obj);
            console.log(result);
            let arr = result.data.records;
            console.log(arr);
            arr = arr.filter(item => {
                return !item.classId;
            })
            this.teacherData = arr.map(item => {
                let obj = {};
                obj.teacherName = item.teacherName;
                obj.id = item.id;
                return obj;
            })
            console.log(this.teacherData);
            console.log(result);
            return result;
        },
        async getGrade() {
            let result = await this.$axios.post(`http://39.105.215.62:8200/grade/findGrades?pageNum=${this.currentPage}&pageSize=${this.pageSize}`, { gradeId: "", gradeName: "", schoolId: this.schoolId });
            console.log(result);
            let arr = result.data.records;
            this.gradeData = arr.map(item => {
                let obj = {};
                obj.gradeName = item.gradeName;
                obj.id = item.gradeId
                return obj
            })
        },
        handleEdit(index, row) {
            console.log(index, row);
            console.log(row);
            this.editInfo.className = row.className;
            this.editInfo.classId = row.classId
            this.editInfo.courseCombination = "";
            this.editInfo.gradeId = row.gradeId;
            this.editInfo.headTeacher = ""
            this.editInfo.schoolId = this.schoolId;
            this.editInfo.id = row.id;
            this.teacherValue = row.teacherId;
            this.dialogFormVisible = true;

        },
        changeInfo(form) {
            this.$refs[form].validate((valid) => {//表单校验
                if (valid) {//valid表示验证是否通过，返回值为布尔类型
                    this.dialogFormVisible = false;
                    // this.courseCombinationValue = '';
                    let obj = this.editInfo;
                    console.log(this.editInfo);
                    console.log(obj);
                    console.log(this.courseCombinationData);
                    console.log(this.courseCombinationValue);
                    console.log(this.courseCombinationData.find(item => item.id == this.courseCombinationValue));
                    let tec = this.courseCombinationData.find(item => item.id == this.courseCombinationValue);
                    console.log(tec);
                    if(tec.combinationName) {
                        obj.combinationName = tec.combinationName;
                    }
                    obj.courseCombination = this.courseCombinationValue;
                    console.log(this.teacherValue);
                    obj.headTeacher = this.teacherValue;
                    console.log(obj);
                    // console.log(obj);
                    this.$axios.post('http://39.105.215.62:8200/class/updateClass', obj)
                        .then(async (res) => {
                            console.log(res);
                            if (res.code == 200) {
                                await this.getList();
                                this.$message({
                                    message: res.msg,
                                    type: 'success'
                                });
                            } else {
                                this.$message.error(res.msg);
                            }   
                        })
                } else {
                    console.log('表格不能为空!!');
                    return false;
                }
            });
        },
        handleDelete(index, row) {
            console.log(index, row.id, row);
            // 提示信息
            this.$confirm('此操作将永久删除此班级, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            })
                .then(async () => {
                    let res = await this.$axios.post(`http://39.105.215.62:8200/class/deleteClass?id=${row.id}`);
                    console.log(res);
                    if (res.code == 200) {
                        await this.getList();
                        if (this.userList.length == 0 && this.currentPage > 1) {
                            this.currentPage = this.currentPage - 1;
                            await this.getList();
                        }
                    }
                })
        },
        handleAdd() {
            if(this.total == 0) {
                this.isSingle = false;
                this.dialogAddVisible = true;
            } else {
                this.$message.error("此时存在班级，不能导入")
            }
        },
        handleSingleClass() {
            this.dialogAddVisible = true;
        },
        async doNext(msg) {
            if (msg) {
                this.dialogAddVisible = false;
                await this.getList();
            }
        },
        async handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val
            await this.getList();
        },
        async handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            await this.getList();
        },
        async findUser() {
            // console.log(schoolId);
            console.log(this.search);
            let res = await this.$axios.post(`http://39.105.215.62:8200/class/selectClasses?pageSize=${this.pageSize}&pageNum=${this.currentPage}`, { gradeId: 1 , className: this.search, schoolId});
            if (res.code == 200) {
                let arr = res.data.records;
                arr.map(item => {
                    if(!item.headTeacher) {
                        item.headTeacher = "暂无班主任"
                    } else {
                        console.log(item.headTeacher);
                        console.log(this.teacherData.find(i => i.id == item.headTeacher));
                        item.headTeacher = this.teacherData.find(i => i.id == item.headTeacher).teacherName;
                    }
                })
                this.total = res.total;
                this.classList = res.data.records;
                this.$message.success(res.msg)
            } else {
                this.$message.error(res.msg)
            }
            this.search = '';
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            console.log(val);
            this.multipleSelection = val;
        },
        async deleteAll() {
            if(this.multipleSelection.length != 0) {
                console.log(this.multipleSelection);
                let deleteArr = this.multipleSelection.map(item => {
                    return item.id
                })
                console.log(deleteArr);
                let data = new FormData();
                data.append("classIds", deleteArr);
                console.log(data);
                console.log(data.get("classIds"));
                // 已实现
                let res = await this.$axios.post("http://39.105.215.62:8200/class/deleteClasses", data);
                if(res.code == 200 ) {
                    await this.getList();
                }
                console.log(res);
            }
        }
    },
    // 生命周期函数--钩子函数一般在初始化页面完成后，再对DOM节点进行相关操作
    async mounted() {
        this.$emit("transfer", this.msg);

        this.schoolId = JSON.parse(sessionStorage.getItem("info")).schoolId;
        
        console.log(this.schoolId);

        await this.getList();
        await this.getCourseCombination();
        await this.getTeachaers();
        await this.getGrade();
    }
}
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.header {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    border-bottom: 1px solid #ccc;
    padding: 5px;
}

.input-with-select {
    width: 400px;
}

.dialogAdd {
    display: flex;
    justify-content: center;
    align-items: center;
}

.pages {
    margin: 20px auto;
}
</style>
  